import { MessageHeaders } from '../Message';
import { StringHelper } from './StringHelper';

export class ResponseParser {
  private constructor() {}
  public static matchAllFolders(str: string) {
    const matches = str.matchAll(/\*\sList\s.*"(.*?)"/gi);
    let matchRes = [...matches];
    return matchRes.map((match) => {
      return match[1];
    });
  }

  // uid size / subject from bcc cc to date
  public static parseFetchHeader(data: string) {
    const parts = [...data.matchAll(/\*\s.*?fetch\s\(([^*]*)\)/gi)];
    const items: MessageHeaders[] = [];
    parts.forEach((match) => {
      const part = match[1];
      const uid = part.matchAll(/uid\s(.*?)\s/gi).next().value?.[1];
      const size = part.matchAll(/RFC822\.SIZE\s(.*?)\s/gi).next().value?.[1];
      const fieldsRegex = /^(date|from|to|subject|cc|bcc|content-type):\s/gim;
      const fieldsMatches = [...part.matchAll(fieldsRegex)].sort((a, b) => a.index! - b.index!);
      let item: MessageHeaders = {
        uid: uid ? uid : '',
        size: size ? Number(size) : undefined,
      };
      for (let i = 0; i < fieldsMatches.length; i++) {
        const propName = fieldsMatches[i][1].toLowerCase();
        const startPos = fieldsMatches[i].index! + propName.length + 1;
        let content: any = '';
        // last one
        if (i === fieldsMatches.length - 1) {
          content = part.substring(startPos);
        } else {
          content = part.substring(startPos, fieldsMatches[i + 1].index!);
        }
        content = content.trim();
        // set props
        switch (propName) {
          case 'date':
            item[propName] = Date.parse(content);
            break;
          case 'from':
          case 'to':
          case 'cc':
          case 'bcc':
          case 'subject':
            item[propName] = StringHelper.decodeHeader(content);
            break;
          case 'content-type':
            item.contentType = content;
            break;
          default:
            break;
        }
      }
      console.log(item);
      items.push(item);
    });
    return items;
  }

  public static parseFetchBody(payload: any): string {
    // Implement parsing logic based on your payload structure
    // For now, just return payload as string if possible
    if (typeof payload === 'string') {
      return payload;
    }
    if (payload && typeof payload.toString === 'function') {
      return payload.toString();
    }
    return '';
  }
}
